#!/usr/bin/env python

import os, sys, getopt
import csv, json

import utility


def analyze_task_usage(task_usage, period_time):
    result = {}
    for task in task_usage:
        start_period = task[0] / period_time
        end_period = (task[1]-1) / period_time
        for i in range(start_period, end_period+1):
            if i not in result:
                result[i] = 0
            result[i] += 1
    return result


# write task statistics to output folder,
def write_task_statistics_to_file(statistics, period_time, target_file):
    records = analyze_task_usage(statistics, period_time)
    if os.path.exists(target_file):
        with open(target_file, "r") as f:
            history_records = json.load(f)
            for r in records:
                if r in history_records:
                    history_records[r] += records[r]
                else:
                    history_records[r] = records[r]
            records = history_records

    with open(target_file, "w") as f:
        json.dump(records, f)


# main framework that trigger the process
def process_data(begin_index, end_index, period_time):
    output_prefix = "output/"
    task_usage_prefix = "task_usage/"
    file_name_prefix = "part-00"
    file_name_suffix = "-of-00500.csv"

    target_file = output_prefix = "output/"+"all_user_of_"+str(period_time)
    for i in range(begin_index, end_index):
        if i < 10:
            file_name = file_name_prefix+"00"+str(i)+file_name_suffix
        elif i < 100:
            file_name = file_name_prefix+"0"+str(i)+file_name_suffix
        else:
            file_name = file_name_prefix+str(i)+file_name_suffix

        task_usage = utility.extract_task_usage(task_usage_prefix+file_name)
        write_task_statistics_to_file(task_usage, period_time, target_file)
    
    utility.sort_dict_in_file(target_file)


def main(argv):
    try:
        opts, args = getopt.getopt(argv[1:], "hp:b:e:")
    except getopt.GetoptError as err:
        print(err)
        sys.exit(2)

    # set default value
    period_time = 300
    begin_index = 0
    end_index = 500

    for o, s in opts:
        # help information
        if o == "-h":
            print "usage: -p <period time>"
            print "       -b <begin package index>"
            print "       -e <end package index>"
            return
        elif o == "-p":
            period_time = int(s)
        elif o == "-b":
            begin_index = int(s)
        elif o == "-e":
            end_index = int(s)

    process_data(begin_index, end_index, period_time)
    

if __name__ == "__main__":
    main(sys.argv)